import router from "./router";
import NProgress from './utils/nprogress'
import userUserStore from './store/modules/user'
import pinia from "./store";
const userStore = userUserStore(pinia)

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    let token = userStore.token
    let username = userStore.username
    if (token) {
        if (to.path == '/login') {
            next({ path: "/" })
        } else {
            if (username) {
                next()
            } else {
                try {
                    await userStore.userInfo()
                    //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
                    next({ ...to });
                    // next()
                } catch (error) {
                    //token过期:获取不到用户信息了
                    //用户手动修改本地存储token
                    await userStore.userLogout()
                    // next({ path: "/login", query: { redirect: to.path } })
                    next({ path: "/login"})
                }
            }
        }
    } else {
        if (to.path == '/login') {
            next()
        } else {
            // next({ path: "/login", query: { redirect: to.path } })
            next({ path: "/login"})
        }
    }
})

router.afterEach((to, from) => {
    NProgress.done()
})